<?php

namespace IDock\Insurance\ZFIC;

use IDock\Common\BaseInterface\BuilderInterface;
use IDock\Common\Tools\XMLTools;
use IDock\Http\Request;
use IDock\Http\Response;
use IDock\Insurance\ZFIC\Request\AllZFICRequest;
use IDock\Insurance\ZFIC\Response\AllZFICResponse;

class Builder implements BuilderInterface
{

    public function getConfig(): array
    {
        return  $this->config;
    }

    protected $ip;

    protected $config;

    protected $chalCode;

    protected $userCode;

    protected $productCode;

    protected $planCode;

    protected $planCodeNew;

    public function execute(Request $request): Response
    {
        /*** @var AllZFICRequest $request */
        $request->loadConfig($this->config);

        $request->setRequestId(md5(uniqid()));

        $data = $this->generate($request);
        $this->getStaffConfig($request);
        $header = [
            'chalCode' => $this->chalCode,
            'userCode' => $this->userCode,
            'productCode' => $this->productCode,
            'planCode' => $this->planCode,
        ];
        if(property_exists($request,'isNewEnergy')){
            if($request->isNewEnergy){
                $header['planCode'] = $this->planCodeNew;//新能源车
            }
        }
        $request->setHeaders($header);

        $request->setPreParameter($data);
        $request->setBizParam($data);
        return $this->request($request);
    }

    public function generate(Request $request): array
    {
        return $request->generate();
    }

    public function sign(Request $request): Request
    {
        return $request;
    }


    public function exceptionResponse($request, $errorMessage): Response
    {
        $response = $request->getResponse();

        $response = new $response;
        $response->setCode('500');
        $response->setError($errorMessage);

        return $response;
    }

    public function request(Request $request): Response
    {
        /**
         * @var AllZFICResponse $response
         */
        $response = $request->request($request);
        $response->setVisitor($request->getVisitor());

        if(!$response->isSuccess()){
            $jsonArr = json_decode($response->getBody(),true);
            $response->setBody($jsonArr);
            $msg = $jsonArr['msg'] ?? '';
            if(empty($msg)){
                $msg = $msg ?: ($jsonArr['message'] ?? '');
            }
            $response->setError($msg);
            if(strpos($response->getError(),'重复投保') === false){
                throw new \Exception($msg);
            }
        }
        $response->printerInit();
        return $response;
    }

    /**
     * 数据加密
     * @param Request $request
     */
    public function encrypt(Request $request)
    {

    }

    public function getStaffConfig(Request $request)
    {
        $request->getStaffConfig($this->chalCode, $this->userCode);
    }
}


